
function moveToPersonalResult(){
    document.getElementById("startView").style.display = "none";
    document.getElementById("loadingStr").style.display = "none";
    document.getElementById("ruleWindow").style.display = "none";
    document.getElementById("fieldArea").style.display = "none";
    document.getElementById("fesitvalResultArea").style.display = "none";
    document.getElementById("personalResultArea").style.display = "";
    gadgets.window.adjustHeight(740);
}

function loadPersonalResult(){
    diaryText[1] = "\r\n\r\n=あなたの診断結果=\r\n";
    voiceText[1] = "【あなたの運動会成績】";
    document.getElementById("startView").style.display = "";
    document.getElementById("loadingStr").style.display = "";
    document.getElementById("nogame").style.display = "none";
    document.getElementById("finishGreeting").style.display = "none";
    document.getElementById("ruleWindow").style.display = "none";
    document.getElementById("fieldArea").style.display = "none";
    document.getElementById("fesitvalResultArea").style.display = "none";
    document.getElementById("personalResultArea").style.display = "none";
    setTimeout(moveToPersonalResult, 5000);
}


function initPersonalResult(){
    if (requestInfo) {
        document.getElementById("personalName").innerHTML = myName;
        document.getElementById("fortuneTitleName").innerHTML = myName;
        requestPersonalResult(myID);
        loadPersonalResult();
    }
    else {
        moveToPersonalResult();
    }
}

/**
 * request personal information to the server
 * @param {Object} myID
 */
function requestPersonalResult(myID){
    var REQUEST_URL = SERVER_NAME + "request/playerinfo";
    var params = {};
    
    params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
    params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;
    
    var post_data = {
        myID: myID
    };
    params[gadgets.io.RequestParameters.POST_DATA] = gadgets.io.encodeValues(post_data);
    gadgets.io.makeRequest(REQUEST_URL, function(response){
        if (response.data) {
            var personalResult = eval("(" + response.data + ")");
            var playerInfo = personalResult["playerInfo"];
            var evaluations = personalResult["evaluations"];
            var playTimeInfo = personalResult["playTimeInfo"];
            var synastryList = personalResult["synastryList"];
            var fortuneList = personalResult["fortuneList"];
            
            var evaluatedFriendsNum = personalResult["evaluatedFriendsNum"];
            playTime = playTimeInfo.playTime;
            
            /* set recent evaluation area*/
            createRecentEvaluation(evaluations);
            
            /* set radar chart area*/
            createRadarChart(playerInfo["categoryPoints"]);
            /* set personal title area*/
            createPersonalTitle(playerInfo["quantityTitle"], playerInfo["qualityTitle"]);
            
            /* set fortune area*/
            document.getElementById("fortuneContent").innerHTML = fortuneList["fortuneContent"];
            document.getElementById("luckyItemName").innerHTML = fortuneList["luckyItem"];
            
            /* set friend area*/
            setPersonalLink(synastryList);
            
            /* once request personal info, no more request*/
            requestInfo = false;
            
            
        }
        else {
            var err = response.errors[0];
            window.alert("タイムアウトしました。ご迷惑をおかけしますが一度運動会の成績ページに戻って再度個人成績ページを表示してください。");
        }
    }, params);
    
}

/**
 * create radar chart based on categoryPoints and evaluatedtime
 * @param {Object} categoryPoints
 */
function createRadarChart(categoryPoints){

    var chartParamater = "";
    for (var i = 0; i < categoryPoints.length; i++) {
        chartParamater = chartParamater + categoryPoints[i] * 20 + ",";
    }
    chartParamater += categoryPoints[0] * 20;
    chartParamater = encodeURI(chartParamater);
    var src = "<img src=\"http://chart.apis.google.com/chart?cht=r&amp;chs=200x200&amp;chls=3,0,0&amp;chxt=x,y&amp;chxl=0:|瞬発力|恋愛運|金銭運|知力|持久力|1:|||||&amp;chm=B,FF990080,0,0,5&amp;chd=t:" + chartParamater + "\"/>";
    document.getElementById("radarChart").innerHTML = src;
    document.getElementById("radarChartStr").innerHTML = "";
    
    // for Diary
    diaryText[1] += "-ステータス-\r\n 瞬発力: " + Math.round(categoryPoints[0] * 10) / 10 + " 恋愛運: " + Math.round(categoryPoints[1] * 10) / 10 + " 金銭運: " + Math.round(categoryPoints[2] * 10) / 10 + " 知力: " + Math.round(categoryPoints[3] * 10) / 10 + " 持久力: " + Math.round(categoryPoints[4] * 10) / 10 + "\r\n\r\n";
    
}

function createPersonalTitle(quantityTitle, qualityTitle){
    var title = quantityTitle + qualityTitle;
    document.getElementById("personalTitle").innerHTML = title;
    // diaryText[1] and voiceText[1] are for personal result page
    diaryText[1] += "-動物占い-\r\n" + title + "\r\n\r\n";
    voiceText[1] += "-動物占い-　　" + title + "　　";
}


function createRecentEvaluation(evaluations){
    var params = {};
    params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = [opensocial.Person.Field.PROFILE_URL];
    var req = opensocial.newDataRequest();
    var itrTime = evaluations.length;
    if (evaluations.length > EVALUATION_TABLE_MAX) {
        itrTime = EVALUATION_TABLE_MAX;
    }
    
    for (var i = 0; i < itrTime; i++) {
        var fieldTitle = evaluations[i]["fieldTitle"];
        var fieldQuestion = evaluations[i]["fieldQuestion"];
        var rank = evaluations[i]["rank"];
        var evaluaterID = evaluations[i]["evaluaterID"];
        var evaluateTime = evaluations[i]["evaluateTime"];
        
        document.getElementById("eval" + i + "0").innerHTML = fieldTitle;
        document.getElementById("eval" + i + "1").innerHTML = rank + "位";
        document.getElementById("eval" + i + "3").innerHTML = evaluateTime;
        
        req.add(req.newFetchPersonRequest(evaluaterID, params), "request" + i);
        
    }
    
    req.send(function(data){
    
        for (var j = 0; j < itrTime; j++) {
            var viewer = data.get("request" + j).getData();
            if (viewer != null) {
            
                var id = viewer.getId();
                var html = "";
                
                if (id in dummyPlayers) {
                    var name = dummyPlayers[id][NICKNAME];
                    var url = dummyPlayers[id][URL];
                    html = name;
                    
                }
                else {
                    var name = viewer.getDisplayName();
                    var url = viewer.getField(opensocial.Person.Field.THUMBNAIL_URL);
                    var purl = viewer.getField(opensocial.Person.Field.PROFILE_URL);
                    html = "<a href=\"" + purl + "\" >" + name + "</a>";
                    
                }
                document.getElementById("eval" + j + "2").innerHTML = html;
            }
            
        }
        
        
    });
    
}

/**
 * create goodFriends, goodPartners, sameTitleFriends information with their name and picture
 * @param {Object} synastryList
 */
function setPersonalLink(synastryList){
    var req = opensocial.newDataRequest();
    for (var htmlIDName in synastryList) {
        needTime = synastryList[htmlIDName]["needTime"]
        // additional contents will show or not
        if (playTime >= needTime) {
            idList = synastryList[htmlIDName]["friendsIDList"]
            if (idList != null) {
                if (idList.length == 0) {
                    document.getElementById(htmlIDName + "Str").innerHTML = NO_FRIEND;
                }
                else {
                
                    for (var i = 0; i < idList.length; i++) {
                        var requestKeys = {};
                        id = idList[i];
                        var params = {};
                        params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = [opensocial.Person.Field.PROFILE_URL];
                        
                        var requestKey = htmlIDName + i;
                        
                        req.add(req.newFetchPersonRequest(id, params), requestKey);
                    }
                }
            }
        }
        else {
            var restTime = needTime - playTime
            document.getElementById(htmlIDName + "Str").innerHTML = NEED_MORE_TIME_PRE + restTime + NEED_MORE_TIME_POST;
        }
    }
    req.send(function(data){
    
        for (var htmlIDName in synastryList) {
            ids = synastryList[htmlIDName]["friendsIDList"];
            
            var namesText = "";
            
            document.getElementById(htmlIDName + "Str").innerHTML = NO_FRIEND;
            for (var j = 0; j < ids.length; j++) {
                var requestKey = htmlIDName + j;
                var item = data.get(requestKey);
                var html = "";
                if (item != null) {
                    var user = item.getData();
                    // to ignore users who don't publish their profile
                    if (user != null) {
                        var name = user.getDisplayName();
                        if (name != undefined) {
                            var url = user.getField(opensocial.Person.Field.THUMBNAIL_URL);
                            var purl = user.getField(opensocial.Person.Field.PROFILE_URL);
                            html += "<a href=\"" + purl + "\" >" + name + "<br><img src=\"" + url + "\" width=40 height=40 \/><\/a>";
                            namesText += " " + name;
                            document.getElementById(htmlIDName + "Str").innerHTML = "";
                            document.getElementById(htmlIDName + j).innerHTML = html;
                        }
                        else {
                            /// NEED TO CHECK
                            var id = user.getId();
                            if (id in dummyPlayers) {
                                name = dummyPlayers[id][NAME];
                                var url = dummyPlayers[id][URL];
                                
                                html += name + "<br><img src=\"" + url + "\" width=40 height=40 \/>";
                                namesText += " " + name;
                                document.getElementById(htmlIDName + "Str").innerHTML = "";
                                document.getElementById(htmlIDName + j).innerHTML = html;
                                
                            }
                            
                        }
                    }
                }
                
                
            }
            
            // for Diary
            if (htmlIDName == "goodPartnerName") {
                diaryText[1] += "-相性抜群のマイミク-\r\n" + namesText + "\r\n\r\n";
            }
            else 
                if (htmlIDName == "goodFriendName") {
                    diaryText[1] += "-相性の良いマイミク-\r\n" + namesText + "\r\n\r\n";
                }
                else 
                    if (htmlIDName == "sameTitleFriendName") {
                        diaryText[1] += "-あなたに近いマイミク-\r\n" + namesText + "\r\n\r\n";
                    }
        }
        
    });
}
